package com.jadcon.bedbreakfast.domain;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Component;

import com.jadcon.bedbreakfast.util.DbUtils;

@Component
public class SuiteRepositoryInMemoryImpl implements SuiteRepository {

	public List<Suite> getSuiteList() {

		List<Suite> suiteList = new ArrayList<Suite>();
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			
			String sql = "SELECT S_id, name, number, beds, cost, description, imageName FROM suite";
			conn = DbUtils.getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while (rs.next()) {

				String name = rs.getString("name");
				int number = rs.getInt("number");
				int beds = rs.getInt("beds");
				int cost = rs.getInt("cost");
				String description = rs.getString("description");
				String imageName = rs.getString("imageName");

				Suite suite = new Suite(name, number, beds, description,
						imageName, cost);

				suiteList.add(suite);

			}
			return suiteList;
			
		} catch (SQLException e) {
			DbUtils.convertCheckedExceptionToRuntime(e);
		} finally {
			DbUtils.close(conn, pstmt, rs);
		}
		return null;
	}

	public void save(Suite suite) {
		// TODO suiteList.add(suite);

	}

	public Suite getNumber(int number) {
		for (Suite suite : getSuiteList()) {
			if (suite.getNumber() == number) {
				return suite;
			}
		}
		return null;

	}

	public Suite getName(String name) {
		for (Suite suite : getSuiteList()) {
			if (suite.getName() == name) {
				return suite;
			}
		}
		return null;

	}

	public Suite getImageName(String name) {
		for (Suite suite : getSuiteList()) {
			if (suite.getImageName() == name) {
				return suite;
			}
		}
		return null;
	}

	public Suite getSuiteByNumber(int number)  {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			String sql = "SELECT name, number, beds, cost, description, imageName, S_id FROM suite where number=?";
			conn = DbUtils.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, number);
			rs = pstmt.executeQuery();
			if (rs.next()) {
				String name = rs.getString("name");
				int number2 = rs.getInt("number");
				int beds = rs.getInt("beds");
				String description = rs.getString("description");
				String imageName = rs.getString("imageName");
				int cost = rs.getInt("cost");
	
				Suite suite = new Suite(name, number2, beds, description, imageName, cost);
				int suiteNumber = suite.getNumber();
				System.out.println("Suite " + suiteNumber + " was selected from database");
				return suite;
			}
		} catch (SQLException e) {
			DbUtils.convertCheckedExceptionToRuntime(e);
		} finally {
			DbUtils.close(conn, pstmt, rs);
		}
		return null;
	}

}
